package com.ruoyi.task

import cn.hutool.core.util.StrUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.ruoyi.ability.Ability
import com.ruoyi.app.common.NetUrlUploadOss
import com.ruoyi.app.common.Sign
import com.ruoyi.back.domain.UserRecord
import com.ruoyi.back.domain.v3.MyRecord
import com.ruoyi.back.service.UserRecordService
import com.ruoyi.back.service.v3.MyRecordService
import com.ruoyi.common.utils.bean.BeanUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.scheduling.annotation.EnableAsync
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit


@Component
@EnableScheduling   // 1.开启定时任务
class Text2PicScheduleTask {

    private val log: Logger = LoggerFactory.getLogger(Text2PicScheduleTask::class.java)

    @Autowired
    private lateinit var myRecordService: MyRecordService

    @Autowired
    private lateinit var netUrlUploadOss: NetUrlUploadOss

    @Autowired
    private lateinit var ability: Ability

    @Scheduled(fixedRate = 3000)
    fun scheduleTask() {
        myRecordService.list(KtQueryWrapper(MyRecord::class.java)
            .eq(MyRecord::status, 0))
            .takeIf { it.isNotEmpty() }
            ?.run {
                forEach {
                    ability.text2PicResult(it.taskId!!).also { log.info("处理结果是 $it") }.let { json ->

                        if (StrUtil.isNotBlank(JSON.parseObject(json).getString("error_msg"))) {
                            myRecordService.updateById(it.apply {
                                this.status = 2
                                errorMsg = when(JSON.parseObject(json).getString("error_code")) {
                                    "282004" -> "请求中包含非法参数或字数超限，请检查后重新尝试"
                                    "282003" -> "缺少必要参数"
                                    "18" -> "QPS 超限额"
                                    "216630" -> "服务器内部错误，请再次请求，如果持续出现此类错误，请通过工单联系技术支持"
                                    "501" -> "文本黄反拦截"
                                    "201" -> "模型生图失败"
                                    "216100" -> "参数不满足格式要求"
                                    "4" -> "错误信息为中文的“请求超限”指所有用户提交的 AI 作画总数超限制"
                                    "13" -> "错误信息为中文的“QPS 超限”指单个用户使用提交请求接口的 QPS 超限"
                                    "15" -> "错误信息为中文的“并发超限”指单个用户使用 AI 作画的并发超限"
                                    "17" -> "错误信息为中文的“用量超限”指单个用户使用 AI 作画的用量超限"
                                    else -> "未知错误"
                                }
                            })
                        }else {
                            JSON.parseObject(json).getJSONObject("data").let { data ->
                                data.getIntValue("status").let { status ->
                                    if (status == 1) {
                                        myRecordService.updateById(it.apply {
                                            this.status = 1

                                            //创建子图片
                                            data.getJSONArray("imgUrls").takeIf { it.isNotEmpty() }
                                                ?.forEach { img ->
                                                    myRecordService.save(MyRecord().apply {
                                                        BeanUtils.copyProperties(it, this)
                                                        pics = run {
                                                            val jsonObject = img as JSONObject
                                                            netUrlUploadOss.upload(jsonObject.getString("image"))
                                                        }
                                                        id = null
                                                        pid = it.id
                                                    })
                                                }
                                        })
                                    }

                                }
                            }
                        }
                    }
                }
            }
    }
}